<script lang="ts">
import { defineComponent, ref } from 'vue'
import * as xml2js from 'xml2js'
import * as yaml from 'js-yaml'

export default defineComponent({
  name: 'ConvertTool',
  props: {
    jsonInput: {
      type: String,
      required: true
    }
  },
  emits: ['converted', 'error'],
  setup(props, { emit }) {
    // 响应式数据
    const showConvertDropdown = ref(false)
    const isConverting = ref(false)

    // 切换转换下拉菜单
    function toggleConvertDropdown(): void {
      showConvertDropdown.value = !showConvertDropdown.value
    }

    // 转换为XML
    async function convertToXml(): Promise<void> {
      if (!props.jsonInput.trim()) {
        emit('error', '请输入JSON内容')
        return
      }

      try {
        isConverting.value = true
        const parsed = JSON.parse(props.jsonInput)
        
        // 使用xml2js的Builder来转换JSON到XML
        const builder = new xml2js.Builder({
          rootName: 'root',
          headless: false,
          renderOpts: {
            pretty: true,
            indent: '  '
          }
        })
        
        const xml = builder.buildObject(parsed)
        emit('converted', xml, 'xml')
        showConvertDropdown.value = false
      } catch (error) {
        emit('error', `转换为XML失败: ${error instanceof Error ? error.message : '未知错误'}`)
      } finally {
        isConverting.value = false
      }
    }

    // 转换为YAML
    async function convertToYaml(): Promise<void> {
      if (!props.jsonInput.trim()) {
        emit('error', '请输入JSON内容')
        return
      }

      try {
        isConverting.value = true
        const parsed = JSON.parse(props.jsonInput)
        const yamlStr = yaml.dump(parsed, {
          indent: 2,
          lineWidth: -1,
          noRefs: true
        })
        emit('converted', yamlStr, 'yaml')
        showConvertDropdown.value = false
      } catch (error) {
        emit('error', `转换为YAML失败: ${error instanceof Error ? error.message : '未知错误'}`)
      } finally {
        isConverting.value = false
      }
    }

    // 转换为格式化JSON
     async function convertToJson(): Promise<void> {
       if (!props.jsonInput.trim()) {
         emit('error', '请输入JSON内容')
         return
       }

       try {
         isConverting.value = true
         const parsed = JSON.parse(props.jsonInput)
         
         // 格式化JSON
         const jsonResult = JSON.stringify(parsed, null, 2)
         
         emit('converted', jsonResult, 'json')
         showConvertDropdown.value = false
       } catch (error) {
         emit('error', `格式化JSON失败: ${error instanceof Error ? error.message : '未知错误'}`)
       } finally {
         isConverting.value = false
       }
     }

    return {
       showConvertDropdown,
       isConverting,
       toggleConvertDropdown,
       convertToXml,
       convertToYaml,
       convertToJson
     }
  }
})
</script>

<template>
  <div class="convert-tool">
    <div class="dropdown">
      <button 
        @click="toggleConvertDropdown" 
        class="btn btn-secondary dropdown-toggle"
        :disabled="isConverting"
      >
        {{ isConverting ? '转换中...' : '🔄 转换格式' }}
      </button>
      <div v-if="showConvertDropdown" class="dropdown-menu">
        <button @click="convertToXml" class="dropdown-item" :disabled="isConverting">
          📄 转换为XML
        </button>
        <button @click="convertToYaml" class="dropdown-item" :disabled="isConverting">
          📝 转换为YAML
        </button>
        <button @click="convertToJson" class="dropdown-item" :disabled="isConverting">
           📝 转换为JSON
         </button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.convert-tool {
  position: relative;
}

.dropdown {
  position: relative;
  display: inline-block;
}

.dropdown-toggle {
  background: #6c757d;
  color: white;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.9rem;
  transition: all 0.2s ease;
}

.dropdown-toggle:hover:not(:disabled) {
  background: #5a6268;
  transform: translateY(-1px);
}

.dropdown-toggle:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.dropdown-menu {
  position: absolute;
  top: 100%;
  left: 0;
  background: white;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  z-index: 1000;
  min-width: 150px;
  margin-top: 4px;
}

.dropdown-item {
  display: block;
  width: 100%;
  padding: 0.5rem 1rem;
  border: none;
  background: none;
  text-align: left;
  cursor: pointer;
  font-size: 0.9rem;
  transition: background-color 0.2s;
}

.dropdown-item:hover:not(:disabled) {
  background-color: #f8f9fa;
}

.dropdown-item:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.dropdown-item:first-child {
  border-top-left-radius: 4px;
  border-top-right-radius: 4px;
}

.dropdown-item:last-child {
  border-bottom-left-radius: 4px;
  border-bottom-right-radius: 4px;
}
</style>